package com.disapand.mybaby.service.impl;

import javax.servlet.http.HttpServletRequest;

import com.disapand.mybaby.exception.ApiException;
import com.disapand.mybaby.service.TokenService;
import com.disapand.mybaby.util.RedisUtil;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import org.springframework.stereotype.Service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @author disapand
 */
@Service
public class TokenServiceImpl implements TokenService {

    private final RedisUtil redisUtil;
    private final ECKey ecKey;

    public TokenServiceImpl(RedisUtil redisUtil) throws JOSEException {
        this.redisUtil = redisUtil;
        this.ecKey = new ECKeyGenerator(Curve.P_256)
                .keyID("123")
                .generate();
    }

    @Override
    public String createToken() {
        String token = IdUtil.simpleUUID();
        redisUtil.setValue(token, token, 60 * 60L);
        return token;
    }

    @Override
    public Boolean checkToken(HttpServletRequest request) throws ApiException {
        String token = request.getHeader("api_idempotent_token");
        if (StrUtil.isEmpty(token)) {
            token = request.getParameter("api_idempotent_token");
            if (StrUtil.isEmpty(token)) {
                throw new ApiException("请求头和参数中未找到 token");
            }
        }

        if (!redisUtil.exsist(token)) {
            throw new ApiException("token 无效");
        }

        redisUtil.delete(token);

        return true;
    }

}
